import os
import shutil
import subprocess
import sys
import venv
from pathlib import Path


def ensure_pip():
    """确保 pip 已安装"""
    try:
        import pip
    except ImportError:
        print("正在安装 pip...")
        # 下载 get-pip.py
        import urllib.request
        urllib.request.urlretrieve(
            "https://bootstrap.pypa.io/get-pip.py",
            "get-pip.py"
        )
        # 安装 pip
        subprocess.run([sys.executable, "get-pip.py"], check=True)
        # 清理临时文件
        os.remove("get-pip.py")
        print("pip 安装完成")


def create_venv():
    """创建虚拟环境"""
    venv_path = Path("venv")

    # 如果虚拟环境已存在，先删除
    if venv_path.exists():
        print("删除现有虚拟环境...")
        try:
            shutil.rmtree(venv_path)
        except Exception as e:
            print(f"删除虚拟环境失败: {e}")
            print("请手动删除 venv 目录后重试")
            sys.exit(1)

    print("创建新的虚拟环境...")
    venv.create(venv_path, with_pip=True)

    # 获取虚拟环境中的 Python 解释器路径
    if sys.platform == "win32":
        python_path = venv_path / "Scripts" / "python.exe"
    else:
        python_path = venv_path / "bin" / "python"

    if not python_path.exists():
        print(f"错误: 虚拟环境创建失败，找不到 Python 解释器: {python_path}")
        sys.exit(1)

    return python_path


def install_deps(python_path):
    """安装依赖"""
    print("安装依赖...")

    # 确保 pip 已安装
    subprocess.run([str(python_path), "-m", "ensurepip", "--upgrade"], check=True)

    # 升级 pip
    subprocess.run([str(python_path), "-m", "pip", "install", "--upgrade", "pip"], check=True)

    # 安装基础依赖
    deps = [
        "setuptools",
        "wheel",
        "requests",
        "fastapi==0.22.0",
        "uvicorn==0.22.0",
        "pydantic",
        "psutil"
    ]

    for dep in deps:
        print(f"安装 {dep}...")
        try:
            subprocess.run(
                [str(python_path), "-m", "pip", "install", "--no-cache-dir", dep],
                check=True
            )
        except subprocess.CalledProcessError as e:
            print(f"安装 {dep} 失败: {e}")
            sys.exit(1)

    # 如果有 requirements.txt，安装其中的依赖
    if Path("requirements.txt").exists():
        print("安装 requirements.txt 中的依赖...")
        try:
            subprocess.run(
                [str(python_path), "-m", "pip", "install", "--no-cache-dir", "-r", "requirements.txt"],
                check=True
            )
        except subprocess.CalledProcessError as e:
            print(f"安装 requirements.txt 失败: {e}")
            sys.exit(1)


def verify_installation(python_path):
    """验证安装"""
    print("\n验证安装...")
    try:
        # 验证关键依赖
        deps = ["requests", "fastapi", "uvicorn", "pydantic", "psutil"]
        for dep in deps:
            subprocess.run(
                [str(python_path), "-c", f"import {dep}"],
                check=True
            )
            print(f"✓ {dep} 安装成功")

        print("\n所有依赖安装成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"\n✗ 验证失败: {e}")
        return False


def main():
    try:
        # 1. 确保系统 Python 有 pip
        ensure_pip()

        # 2. 创建虚拟环境
        python_path = create_venv()

        # 3. 安装依赖
        install_deps(python_path)

        # 4. 验证安装
        if verify_installation(python_path):
            print("\n环境设置完成！")
            print(f"虚拟环境 Python 路径: {python_path}")
            print("\n使用说明:")
            print("1. 激活虚拟环境:")
            if sys.platform == "win32":
                print("   .\\venv\\Scripts\\activate")
            else:
                print("   source venv/bin/activate")
            print("2. 运行测试:")
            print("   python test_all.py")
            sys.exit(0)
        else:
            print("\n环境设置失败，请检查错误信息")
            sys.exit(1)

    except Exception as e:
        print(f"\n设置过程出错: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
